<script setup lang="ts">
import { useI18n } from 'vue-i18n'
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { debounce } from 'lodash-es'

import { useMqtt } from "@/hooks/useMqtt";
const { connect, subscribe, unsubscribe } = useMqtt();

const lastActive = ref(Date.now())
let timer: NodeJS.Timeout | null = null

// 使用 Lodash 的 debounce 函数（500ms间隔）
const updateActivity = debounce(() => {
  lastActive.value = Date.now()
}, 500, { leading: true, trailing: true })

const i18n = useI18n()

watch(i18n.locale, (locale: any) => {
  if (locale === 'zh-Hans') {
    document.documentElement.setAttribute('lang', 'zh-Hans-CN')
  }
  if (locale === 'en') {
    document.documentElement.setAttribute('lang', 'en-US')
  }
}, { immediate: true })

const checkInactivity = () => {
  const inactiveTime = Date.now() - lastActive.value
  if (inactiveTime > 180000) { // 3分钟无操作后执行刷新
    location.reload()
  }
}

onMounted(() => {
  // 监听用户操作（使用防抖）
  window.addEventListener('mousemove', updateActivity)
  window.addEventListener('keydown', updateActivity)
  window.addEventListener('scroll', updateActivity)
  window.addEventListener('click', updateActivity)

  // 每30分钟检查一次
  timer = setInterval(checkInactivity, 30 * 60 * 1000)

  // 初始检查
  checkInactivity()


	connect();
	/** 监听相机告警事件 */
	subscribe("plc_server/camera/trigger/video", (topic: string, data: string) => {
		// TODO: 判断当前路由是否在报警页面，如果不是则跳转
	});
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
    timer = null
  }
  // 取消防抖函数的待执行操作
  updateActivity.cancel()
  window.removeEventListener('mousemove', updateActivity)
  window.removeEventListener('keydown', updateActivity)
  window.removeEventListener('scroll', updateActivity)
  window.removeEventListener('click', updateActivity)
})
</script>

<template>
  <router-view />
</template>

<style lang="scss">
#app {
  height: 100vh;
}
</style>